<template>
  <div class="message-wrapper" :class="{ 'sent': msg.isSent, 'received': !msg.isSent, 'system-like': msg.messageType !== 'USER' && msg.messageType !== 'IMAGE' }">
    <div class="msg-avatar">
      <img v-if="avatar" :src="avatar" class="avatar-msg-img" :alt="msg.displaySender + '头像'" />
      <div v-else class="avatar-msg-default">
        <span class="avatar-initial">{{ msg.displaySender ? msg.displaySender.charAt(0).toUpperCase() : '?' }}</span>
      </div>
    </div>
    <div class="msg-content-wrapper">
      <div class="msg-sender" :class="{ 'sender-sent': msg.isSent, 'sender-received': !msg.isSent }">{{ msg.displaySender }}</div>
      <div class="msg-text-bubble">
        <div v-if="msg.messageType === 'IMAGE'" class="image-message-content">
          <img
              :src="msg.content"
              alt="聊天图片"
              class="chat-image-display"
              @click="handleImageClick"
          @error="handleImageError"
          />
        </div>
        <p v-else class="msg-text" v-html="linkify(msg.content)"></p>
      </div>
      <div class="msg-timestamp">{{ formatTimestamp(msg.timestamp) }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ArtisticMessage',
  props: {
    msg: {
      type: Object,
      required: true
    },
    avatar: {
      type: String,
      default: null
    }
  },
  emits: ['image-preview-requested'], // ADDED: Declare emitted event
  methods: {
    formatTimestamp(timestampStr) {
      if (!timestampStr) return '';
      let dateInput = timestampStr;
      if (typeof timestampStr === 'string') {
        const hasZ = timestampStr.endsWith('Z');
        const hasOffset = /([+\-])\d{2}:\d{2}$/.test(timestampStr);
        if (!hasZ && !hasOffset) {
          if (timestampStr.includes('T')) {
            dateInput = timestampStr + 'Z';
          } else if (timestampStr.includes(' ') && timestampStr.includes(':') && timestampStr.includes('-')) {
            dateInput = timestampStr.replace(' ', 'T') + 'Z';
          }
        }
      }
      const date = new Date(dateInput);
      if (isNaN(date.getTime())) {
        console.warn('ArtisticMessage: Invalid timestamp received. Original:', timestampStr, 'Attempted to parse:', dateInput);
        return "时间未知";
      }
      return date.toLocaleTimeString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      });
    },
    linkify(text) {
      const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])|(\bwww\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(urlPattern, function(url) {
        const KLink = url.startsWith('www.') ? 'http://' + url : url;
        return `<a href="${KLink}" target="_blank" rel="noopener noreferrer" class="embedded-link">${url}</a>`;
      });
    },
    // MODIFIED: Renamed and changed to emit event
    handleImageClick() {
      if (this.msg.content) {
        this.$emit('image-preview-requested', this.msg.content);
      }
    },
    handleImageError(event) {
      console.warn('图片加载失败:', event.target.src);
    }
  }
}
</script>

<style scoped>
/* Make links in messages look good */
:deep(.embedded-link) {
  color: #87CEFA;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s ease, text-shadow 0.2s ease;
}
:deep(.embedded-link:hover) {
  color: #FFD700;
  text-decoration: underline;
  text-shadow: 0 0 5px #FFD700;
}


.message-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  margin-bottom: 18px;
  opacity: 0;
  animation: fadeInMessage 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}

@keyframes fadeInMessage {
  0% {
    opacity: 0;
    transform: translateY(20px) scale(0.95);
  }
  70% {
    opacity: 0.8;
    transform: translateY(-5px) scale(1.02);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.message-wrapper.sent {
  flex-direction: row-reverse;
}
.message-wrapper.system-like {
  font-style: italic;
  filter: brightness(0.9);
}

.msg-avatar {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  background-color: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(255, 255, 255, 0.25);
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  transition: transform 0.3s ease;
}
.msg-avatar:hover {
  transform: scale(1.1);
}


.avatar-msg-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-msg-default {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 1.3rem;
}
.received .avatar-msg-default {
  background: linear-gradient(135deg, #7209b7, #f72585, #b5179e);
}
.sent .avatar-msg-default {
  background: linear-gradient(135deg, #4361ee, #3a0ca3, #480ca8);
}
.avatar-initial {
  text-shadow: 1px 1px 3px rgba(0,0,0,0.4);
}


.msg-content-wrapper {
  display: flex;
  flex-direction: column;
  max-width: calc(75% - 10px);
}

.sent .msg-content-wrapper {
  align-items: flex-end;
}

.received .msg-content-wrapper {
  align-items: flex-start;
}

.msg-text-bubble {
  padding: 14px 20px;
  border-radius: 20px;
  color: white;
  position: relative;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25), 0 2px 5px rgba(0,0,0,0.15);
  word-wrap: break-word;
  overflow-wrap: break-word;
  line-height: 1.6;
  transition: transform 0.2s ease-out;
}
.msg-text-bubble:hover {
  transform: translateY(-2px);
}

.image-message-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.chat-image-display {
  max-width: 100%;
  max-height: 300px;
  border-radius: 12px;
  object-fit: cover;
  cursor: pointer;
  display: block;
  background-color: rgba(0,0,0,0.1);
}
.msg-text-bubble:has(> .image-message-content) {
  padding: 8px;
}


.received .msg-text-bubble {
  background: rgba(255, 255, 255, 0.18);
  border-bottom-left-radius: 6px;
  animation: receivedBubbleGlow 3s infinite alternate ease-in-out;
}
@keyframes receivedBubbleGlow {
  0% { box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25), 0 0 5px rgba(200,200,255,0.1); }
  100% { box-shadow: 0 5px 18px rgba(0, 0, 0, 0.3), 0 0 12px rgba(200,200,255,0.25); }
}

.sent .msg-text-bubble {
  background: linear-gradient(135deg, #4e20ac, #733bd8);
  color: #ffffff;
  border-bottom-right-radius: 6px;
  position: relative;
  overflow: hidden;
}
.sent .msg-text-bubble::after {
  content: '';
  position: absolute;
  top: -10%;
  left: -150%;
  width: 80%;
  height: 120%;
  background: linear-gradient(
      100deg,
      rgba(255, 255, 255, 0) 20%,
      rgba(255, 255, 255, 0.15) 50%,
      rgba(255, 255, 255, 0) 80%
  );
  transform: skewX(-25deg);
  animation: sentBubbleShine 3.5s infinite linear;
  animation-delay: calc(var(--index, 0) * 0.1s);
}

@keyframes sentBubbleShine {
  0% { left: -150%; }
  60% { left: 150%; }
  100% { left: 150%; }
}


.msg-sender {
  font-size: 0.85rem;
  font-weight: 600;
  margin-bottom: 6px;
  padding: 0 8px;
  color: rgba(255, 255, 255, 0.75);
  text-shadow: 0 1px 1px rgba(0,0,0,0.1);
}

.msg-text {
  font-size: 1.05rem;
  white-space: pre-wrap;
}

.msg-timestamp {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.55);
  margin-top: 6px;
  padding: 0 8px;
}

.sent .msg-timestamp {
  align-self: flex-end;
}

.received .msg-timestamp {
  align-self: flex-start;
}

.msg-text-bubble::before {
  content: '';
  position: absolute;
  bottom: -1px;
  width: 18px;
  height: 18px;
  background: inherit;
  clip-path: polygon(0% 100%, 100% 100%, 50% 0%);
  transform-origin: bottom;
  z-index: -1;
}

.received .msg-text-bubble::before {
  left: -8px;
  transform: rotate(35deg) skewX(-18deg);
  background: rgba(255, 255, 255, 0.18);
}

.sent .msg-text-bubble::before {
  right: -8px;
  transform: rotate(-35deg) skewX(18deg);
  background: linear-gradient(135deg, #4e20ac, #733bd8);
}
</style>
